"use strict"

const mvc = require('cosjs.mvc');
const { iconFrame } = require('../../../share/format/role');

/**
 * @name mainStory
 * 主线剧情
 */

/**
 * @name getMainStoryData
 * 获取主线剧情的历史信息
 */
exports.getMainStoryData = async function () {
    //从mainStory里获取主线战斗的历史信息
    let mainStoryModel = this.model.mongo("mainStory", this.sid, this.uid);
    return mainStoryModel.mget().then(ret => {
        if (!ret) {
            return this.quick_error('mainStoryData empty');
        }
        this.updater.cache(ret);
        return ret;
    });
}

/**
 * @name startMainStory
 * @param int id 关卡ID
 * 创建主线战斗
 */
exports.startMainStory = async function () {
    //获取关卡ID
    const id = this.get('id', 'int');
    if (!id) {
        return this.quick_error("M2saghge10", 'id empty');
    }
    let chapterID = Math.floor(id / 100);
    //获取主线战斗的历史信息
    this.updater.mainStory.key(chapterID);
    //从mainChapter表里判断是否拥有前置章节
    let mainChapterConfig = this.config("mainChapter", chapterID);
    if (!mainChapterConfig) {
        return this.quick_error("M2saghge200", 'mainChapterConfig empty');
    }
    //获取关卡配置
    let mainNodeConfig = this.config("mainNode", id);
    if (!mainNodeConfig) {
        return this.quick_error('mainCha"M2saghge200", pterConfig empty');
    }
    if (mainNodeConfig.front) {
        //获取前置章节的数据
        let forntChapterID = Math.floor(mainNodeConfig.front / 100);
        this.updater.mainStory.key(forntChapterID);
    }
    await this.updater.data();

    if (mainNodeConfig.front) {
        //有前置章节的需求
        //获取前置章节的数据
        let forntChapterID = Math.floor(mainNodeConfig.front / 100);
        let frontData = this.updater.mainStory.get(forntChapterID) || {};
        //判断前置章节是否已经通关
        if (!frontData.hasOwnProperty("stageData")) {
            return this.quick_error("M2saghge200", 'frontChapter not pass');
        }
        // console.log("frontData", frontData);
        if (!frontData.stageData.hasOwnProperty(mainNodeConfig.front)) {
            return this.quick_error("M2saghge201", 'frontStage not pass', mainNodeConfig.front);
        }
        if (!frontData.stageData[mainNodeConfig.front].pass) {
            return this.quick_error("M2saghge202", 'frontStage not pass', mainNodeConfig.front);
        }
    }
    let data = this.updater.mainStory.get(chapterID) || {};

    //判断是否可以进入关卡
    let mainStoryCacheModel = this.model.redis("mainStory", this.sid);
    if (!mainNodeConfig.front) {
        // console.log("maindata set redis data:", { "id": chapterID, "stageID": id })
        mainStoryCacheModel.set(this.uid, { "id": chapterID, "stageID": id });
        return data;
    } else {
        // if (!data.hasOwnProperty("stageData")) {
        //     return this.quick_error("M2saghge200", 'frontStage not pass', mainNodeConfig.front);
        // }
        // if (!data.stageData.hasOwnProperty(mainNodeConfig.front)) {
        //     return this.quick_error("M2saghge201", 'frontStage not pass', mainNodeConfig.front);
        // }

        // console.log("maindata set redis data:", { "id": chapterID, "stageID": id })
        mainStoryCacheModel.set(this.uid, { "id": chapterID, "stageID": id });
        return data;
    }
}


/**
 * @name endMainStory
 * @param json data 通关数据
 * 结算主线战斗
 */
exports.endMainStory = async function () {
    //获取通关标识
    const historyData = this.get('data', 'json');
    //从redis数据库中获取数据
    let mainStoryCacheModel = this.model.redis("mainStory", this.sid);
    let mainStoryCache = await mainStoryCacheModel.get(this.uid);
    if (!mainStoryCache) {
        return this.error('mainStoryCache empty');
    }
    //获取主线战斗的历史信息
    const chapterID = mainStoryCache.id;
    const stageID = mainStoryCache.stageID;
    // console.log("main data stageID:", stageID);
    this.updater.mainStory.key(chapterID);
    await this.updater.data();
    let data = this.updater.mainStory.get(chapterID) || {};
    //获取关卡配置
    let mainNodeConfig = this.config("mainNode", stageID);
    if (!mainNodeConfig) {
        return this.quick_error('mainChapterConfig empty');
    }
    //判断本关卡的历史通关情况
    //TODO:根据拼分表计算本次分数 遍历mainNodeConfig里scoreRequire
    let score = 0;
    for (let i in mainNodeConfig.scoreRequire) {
        //根据值去scoreRequire表里取出评分字段
        let scoreConfig = this.config("scoreRequire", mainNodeConfig.scoreRequire[i]);
        if (!scoreConfig) {
            return this.quick_error('scoreConfig empty');
        }
        if (scoreConfig.compare == 0) {
            if (historyData[scoreConfig.key] >= scoreConfig.val) {
                score++;
            }
        } else if (scoreConfig.compare == 1) {
            // console.log("key:", scoreConfig.key);
            // console.log("historyData[scoreConfig.key]:", historyData[scoreConfig.key])
            // console.log("kscoreConfig.valey:", scoreConfig.val);
            if (historyData[scoreConfig.key] <= scoreConfig.val) {
                score++;
            }
        } else {
            return this.quick_error('historyData.compare error');
        }
    }
    //保存数据
    this.updater.record.add("63" + stageID, 1);
    this.updater.record.add(70, 1);
    if (!data.hasOwnProperty("stageData")) {
        data.stageData = {};
        data.stageData[stageID] = { "pass": 1, "score": score, "data": historyData };
        //结算首通奖励
        for (let item of mainNodeConfig["itemDrop"]) {
            this.updater.add(item.id, item.num);
        }
        this.updater.role.add('hangPoint', 1);
        this.updater.mainStory.set(mainStoryCache.id, "stageData", data.stageData);
        this.updater.add(mainNodeConfig.box, mainNodeConfig.count);
        if (chapterID == "101") {
            this.updater.record.add("62" + chapterID, score);
        }
    } else {
        if (!data.stageData.hasOwnProperty(stageID)) {
            this.updater.add(mainNodeConfig.box, mainNodeConfig.count);
        }
        if (!data.stageData.hasOwnProperty(stageID)) {
            for (let item of mainNodeConfig["itemDrop"]) {
                this.updater.add(item.id, item.num);
            }
            this.updater.role.add('hangPoint', 1);
            data.stageData[stageID] = { "pass": 1, "score": score, "data": historyData };
        } else {
            if (data.stageData[stageID].score < score) {
                if (chapterID == "101") {
                    this.updater.record.add("62" + chapterID, score - data.stageData[stageID].score);
                }
                data.stageData[stageID].score = score;
            }
            data.stageData[stageID].data = historyData;
        }
        this.updater.mainStory.set(mainStoryCache.id, "stageData." + stageID, data.stageData[stageID]);
    }

    //删除缓存
    mainStoryCacheModel.del(this.uid);
    return this.updater.save();
}

/**
 * @name getMainStoryReward
 * @param int id 章节ID
 * @param array rewardIDList 奖励ID列表
 * 领取主线剧情奖励
 */
exports.getMainStoryReward = async function () {
    //获取关卡ID
    const id = this.get('id', 'int');
    if (!id) {
        return this.error('id empty');
    }
    //获取奖励ID列表
    const rewardIDList = this.get('rewardIDList', 'array');
    if (!rewardIDList) {
        return this.error('rewardIDList empty');
    }
    //获取主线战斗的历史信息
    this.updater.mainStory.key(id);
    await this.updater.data();
    let data = this.updater.mainStory.get(id) || {};
    if (!data.hasOwnProperty("id")) {
        return this.quick_error('mainStoryData empty');
    }
    //计算总分
    let score = 0;
    for (let key in data.stageData) {
        if (data.stageData.hasOwnProperty(key)) {
            score += data.stageData[key].score;
        }
    }
    //判断是否可以领取奖励
    let mainChapterConfig = this.config("mainChapter", id);
    if (!mainChapterConfig) {
        return this.quick_error("M2saghge200", 'mainChapterConfig empty');
    }
    //判断是否已经领取过奖励
    //领取奖励
    let flag = 0;
        for (let i = 0; i < rewardIDList.length; i++) {
        for (let j = 0; j < data.reward.length; j++) {
            if (data.reward[j] == rewardIDList[i]) {
                return this.quick_error("M2saghge200", 'rewardIDList has been get');
            }
        }
        // console.log("main data reward:", mainChapterConfig.itemList[rewardIDList[i]]);
        if (mainChapterConfig.itemList[rewardIDList[i]] && mainChapterConfig.itemList[rewardIDList[i]].score <= score) {
            this.updater.add(mainChapterConfig.itemList[rewardIDList[i]].id, mainChapterConfig.itemList[rewardIDList[i]].count);
            data.reward.push(rewardIDList[i]);
            flag = 1;
        }
    }
    //保存数据
    // await mainStoryModel.set(mainStoryModel.ObjectID(this.uid, chapterID), mainStoryData);
    if (flag == 1) {
        this.updater.mainStory.set(id, "reward", data.reward);
    }
    //数据落地
    return this.updater.save();
}

